<template>
  <div class="login-container">
    <!-- 登录卡片 -->
    <div class="login-card">
      <!-- 登录标题区域 -->
      <div class="login-header">
        <h1 class="login-title">登 录</h1>
        <p class="login-subtitle">请登录您的账号</p>
      </div>

      <!-- 登录表单 -->
      <form @submit.prevent="handleLogin" class="login-form">
        <!-- 用户名输入 -->
        <div class="form-group">
          <label for="username" class="form-label">用户名</label>
          <div class="input-wrapper">
            <i class="icon user-icon"></i>
            <input
                type="text"
                id="username"
                v-model="form.username"
                @blur="validateField('username')"
                class="form-input"
                placeholder="请输入用户名"
            >
          </div>
          <p v-if="errors.username" class="error-message">{{ errors.username }}</p>
        </div>

        <!-- 密码输入 -->
        <div class="form-group">
          <label for="password" class="form-label">密码</label>
          <div class="input-wrapper">
            <i class="icon lock-icon"></i>
            <input
                :type="showPassword ? 'text' : 'password'"
                id="password"
                v-model="form.password"
                @blur="validateField('password')"
                class="form-input"
                placeholder="请输入密码"
            >
            <button
                type="button"
                class="toggle-password"
                @click="showPassword = !showPassword"
            >
              <i class="icon" :class="showPassword ? 'eye-icon' : 'eye-off-icon'"></i>
            </button>
          </div>
          <p v-if="errors.password" class="error-message">{{ errors.password }}</p>
        </div>

        <!-- 记住密码和忘记密码 -->
        <div class="form-actions">
          <label class="remember-me">
            <input type="checkbox" v-model="rememberMe">
            <span>记住我</span>
          </label>
          <a href="#" class="forgot-password">忘记密码?</a>
        </div>

        <!-- 登录按钮 -->
        <button
            type="submit"
            class="login-button"
            :disabled="isSubmitting"
        >
          <span v-if="!isSubmitting">登录</span>
          <span v-if="isSubmitting">登录中...</span>
        </button>

        <!-- 注册链接 -->
        <div class="register-prompt">
          还没有账号? <a href="#" class="register-link">立即注册</a>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
// 1. 引入 Element UI 的 Message（用于给用户弹提示，初学者必备）
// 如果你没装 Element UI，先执行：npm install element-ui -S，再在 main.js 里引入
import { Message } from 'element-ui'
import { login } from '@/api/user'

export default {
  name: "LoginView",
  data() {
    return {
      // 表单数据（不变）
      form: {
        username: '',
        password: ''
      },
      // 错误信息（不变）
      errors: {},
      // 是否显示密码（不变）
      showPassword: false,
      // 是否记住密码（不变）
      rememberMe: false,
      // 是否正在提交（防止重复点击）
      isSubmitting: false
    };
  },
  methods: {
    // 验证单个字段（不变）
    validateField(field) {
      this.errors[field] = '';
      if (field === 'username' && !this.form.username.trim()) {
        this.errors[field] = '用户名不能为空';
      }
      if (field === 'password') {
        if (!this.form.password) {
          this.errors[field] = '密码不能为空';
        } else if (this.form.password.length < 6) {
          this.errors[field] = '密码长度不能少于6位';
        }
      }
    },

    // 验证整个表单（不变）
    validateForm() {
      let isValid = true;
      this.errors = {};
      // 验证用户名
      if (!this.form.username.trim()) {
        this.errors.username = '用户名不能为空';
        isValid = false;
      }
      // 验证密码
      if (!this.form.password) {
        this.errors.password = '密码不能为空';
        isValid = false;
      } else if (this.form.password.length < 6) {
        this.errors.password = '密码长度不能少于6位';
        isValid = false;
      }
      return isValid;
    },

    // 2. 处理登录（核心修改：去掉 token，只判断用户是否存在）
    handleLogin() {
      if (!this.validateForm()) return;
      this.isSubmitting = true;

      login(this.form)
          .then(res => {
            console.log("后端返回结果：", res);
            if (res.code === 200 && res.data) {
              // 关键：登录成功，把后端返回的用户信息存入 Vuex
              this.$store.commit('SET_USER_INFO', res.data);

              // 原有逻辑：记住用户名、跳转首页
              if (this.rememberMe) {
                localStorage.setItem('savedUsername', this.form.username);
              } else {
                localStorage.removeItem('savedUsername');
              }
              this.$router.push('/home');
              Message.success('登录成功！');
            } else {
              Message.error(res.msg || '用户名或密码错误');
            }
          })
          .catch(err => {
            console.error("登录请求出错：", err);
            Message.error('网络异常！先检查后端是否启动');})
          .finally(() => { this.isSubmitting = false; });
    }
  },

  // 3. 页面加载时：自动填充“记住我”的用户名（初学者友好，不用重复输入）
  mounted() {
    const savedName = localStorage.getItem('savedUsername');
    if (savedName) {
      this.form.username = savedName;
      this.rememberMe = true; // 同步“记住我”勾选状态
    }
  }
};
</script>

<style scoped>
/* 样式部分完全不变，直接保留 */
.login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  box-sizing: border-box;
}

.login-card {
  width: 100%;
  max-width: 400px;
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  padding: 40px 30px;
  box-sizing: border-box;
  animation: fadeIn 0.5s ease;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-title {
  margin: 0 0 10px 0;
  color: #333333;
  font-size: 24px;
  font-weight: 600;
}

.login-subtitle {
  margin: 0;
  color: #666666;
  font-size: 14px;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  text-align: left;
  gap: 8px;
}

.form-label {
  font-size: 14px;
  color: #333333;
  font-weight: 500;
}

.input-wrapper {
  position: relative;
}

.form-input {
  width: 100%;
  padding: 14px 16px 14px 44px;
  border: 1px solid #dddddd;
  border-radius: 8px;
  font-size: 15px;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
}

.icon {
  position: absolute;
  left: 14px;
  top: 50%;
  transform: translateY(-50%);
  color: #999999;
  width: 18px;
  height: 18px;
}

.user-icon::before {
  content: '👨‍💻';
  font-style: normal;
}

.lock-icon::before {
  content: '🔒';
  font-style: normal;
}
.toggle-password {
  position: absolute;
  right: 14px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  padding: 0;
  color: #999999;
  transition: color 0.3s ease;
}

.toggle-password:hover {
  color: #667eea;
}

.error-message {
  margin: 0;
  font-size: 13px;
  color: #e53e3e;
  height: 16px;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 5px;
}

.remember-me {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #666666;
  cursor: pointer;
}

.forgot-password {
  font-size: 14px;
  color: #667eea;
  text-decoration: none;
  transition: color 0.3s ease;
}

.forgot-password:hover {
  color: #556bda;
  text-decoration: underline;
}

.login-button {
  width: 100%;
  padding: 14px;
  background-color: #667eea;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 10px;
}

.login-button:hover {
  background-color: #556bda;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.login-button:active {
  transform: translateY(0);
}

.login-button:disabled {
  background-color: #a0aec0;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.register-prompt {
  text-align: center;
  margin-top: 25px;
  font-size: 14px;
  color: #666666;
}

.register-link {
  color: #667eea;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.3s ease;
}

.register-link:hover {
  color: #556bda;
  text-decoration: underline;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>